﻿using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
#region 准备demo数据表格
DataTable dt =new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Age");
dt.Columns.Add("Gender");
dt.Columns.Add("Mobile");
dt.Columns.Add("Email");
for (int i = 0; i < 10; i++)
{
    var row = dt.NewRow();
    row["Name"] = "张三" + i;
    row["Age"] = 10 + i;
    row["Gender"] = i % 2 == 0 ? "男" : "女";
    row["Mobile"] = 13812345678 + i;
    row["Email"] = $"zhangsan{i}@demo.com";
    dt.Rows.Add(row);
}
#endregion

//保存目录
string filePath = "user.xlsx";
string sheetName = "user";
//1.创建工作簿
IWorkbook workbook = new XSSFWorkbook();
//2.创建sheet表格
ISheet sheet=workbook.CreateSheet(sheetName);
//3.创建表头，第一行
IRow headerRow = sheet.CreateRow(0);
var columns = dt.Columns;
//4.写入表头内容
for(int i = 0; i < columns.Count; i++)
{
    //创建单元格，并写入内容
    ICell cell = headerRow.CreateCell(i);
    cell.SetCellValue(columns[i].ColumnName);
}
//5.遍历数据表格行数据，并创建数据行写入数据内容
for(int i=0;i<dt.Rows.Count; i++)
{
    var row=dt.Rows[i];
    IRow dataRow=sheet.CreateRow(i+1);
    for(int j=0;j<columns.Count; j++)
    {
        ICell cell=dataRow.CreateCell(j);
        var value = row[j];
        cell.SetCellValue((string)value);
    }
}
//6.保存本地
using(FileStream fs=new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
    workbook.Write(fs);
}
Console.WriteLine("finish!");